package com.wise.gemmes.controller.section;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import com.wise.gemmes.entity.post.PostEntity;
import com.wise.gemmes.entity.section.SectionEntity;
import com.wise.gemmes.entity.sectioncate.SectioncateEntity;
import com.wise.gemmes.service.section.SectionServiceI;

import net.sf.json.JSONArray;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import java.io.IOException;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 工段信息
 * @author zhangdaihao
 * @date 2018-03-20 09:10:55
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/sectionController")
public class SectionController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SectionController.class);

	@Autowired
	private SectionServiceI sectionService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工段信息列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/wise/gemmes/section/sectionList");
	}
	
	@RequestMapping(params = "mlist")
	public ModelAndView mlist(HttpServletRequest request) {
		return new ModelAndView("com/wise/gemmes/section/sectionManage");
	}
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagridbytype")
	public void datagridbytype(SectionEntity section,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(SectionEntity.class, dataGrid);
		//查询条件组装器
		String type = request.getParameter("type");
		
		if((!type.equals(null))||(!type.equals(""))) {
			cq.eq("sectionCategory", type);
			cq.add();
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, section, request.getParameterMap());
		this.sectionService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	@RequestMapping(params = "datagrid")
	public void datagrid(SectioncateEntity section,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(SectioncateEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, section, request.getParameterMap());
		this.sectionService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	@RequestMapping(params = "mdatagrid")
	public void mdatagrid(SectionEntity section,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(SectionEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, section, request.getParameterMap());
		this.sectionService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除工段信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(SectionEntity section, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		section = systemService.getEntity(SectionEntity.class, section.getId());
		message = "工段信息删除成功";
		sectionService.delete(section);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加工段信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(SectionEntity section, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(section.getId())) {
			message = "工段信息更新成功";
			SectionEntity t = sectionService.get(SectionEntity.class, section.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(section, t);
				sectionService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "工段信息更新失败";
			}
		} else {
			message = "工段信息添加成功";
			sectionService.save(section);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 工段信息列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(SectionEntity section, HttpServletRequest req) {
		String type = req.getParameter("type");
		req.setAttribute("type", type);
		if (StringUtil.isNotEmpty(section.getId())) {
			section = sectionService.getEntity(SectionEntity.class, section.getId());
			req.setAttribute("sectionPage", section);
		}
		return new ModelAndView("com/wise/gemmes/section/section");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<SectionEntity> list() {
		List<SectionEntity> listSections=sectionService.getList(SectionEntity.class);
		return listSections;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		SectionEntity task = sectionService.get(SectionEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody SectionEntity section, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<SectionEntity>> failures = validator.validate(section);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		sectionService.save(section);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = section.getId();
		URI uri = uriBuilder.path("/rest/sectionController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody SectionEntity section) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<SectionEntity>> failures = validator.validate(section);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		sectionService.saveOrUpdate(section);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		sectionService.deleteEntityById(SectionEntity.class, id);
	}

	/**
	 * 工段表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "sectionlist")
	public ModelAndView equiplist(HttpServletRequest request) {
		String typeId = request.getParameter("type_id");
		request.setAttribute("type_id", typeId);
		return new ModelAndView("com/wise/gemmes/section/section_List");
	}
	
	/**
	 * 页面加载时返回类别信息
	 * */
	@RequestMapping(params = "getSeccate", produces = "application/json")
	public void getSeccate(HttpServletResponse response, HttpServletRequest request) throws IOException{
		JSONArray jsonArray = new JSONArray();
		StringBuffer strb = new StringBuffer();
		String type = request.getParameter("type");
		if(type.equals("")) {
			String hql = "from SectioncateEntity s";
			List<SectioncateEntity> list = systemService.findHql(hql);
			for(SectioncateEntity se:list) {
				strb.append("{\"id\":\"");
				strb.append(se.getId());
				strb.append("\",\"name\":\"");
				strb.append(se.getName());
				strb.append("\",\"code\":\"");
				strb.append(se.getCode());
				strb.append("\"}");
				
				jsonArray.add(strb.toString());
				strb.setLength(0);
				
			}
		}else {
			String hql = "from SectioncateEntity s where code = '" + type + "'";
			List<SectioncateEntity> list = systemService.findHql(hql);
			for(SectioncateEntity se:list) {
				strb.append("{\"id\":\"");
				strb.append(se.getId());
				strb.append("\",\"name\":\"");
				strb.append(se.getName());
				strb.append("\",\"code\":\"");
				strb.append(se.getCode());
				strb.append("\"}");
				
				jsonArray.add(strb.toString());
				strb.setLength(0);
				
			}
		}
			
		response.getWriter().write(jsonArray.toString());
		response.flushBuffer();
	}
}
